import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import lejos.pc.comm.NXTConnector;


public class ServeurCommunication extends Thread {


	private DataInputStream inputStream;
	private DataOutputStream outputStream;
	private Serveur serveur;
	private boolean isRunning; 
	


	public ServeurCommunication(Serveur serveur) {
		this.serveur = serveur;
	}
	
	public void connexion(String brique){
		NXTConnector conn = new NXTConnector();
		
		// Connexion à la brique NXT
		boolean connected = conn.connectTo("btspp://"+brique);
		if (!connected) {
			serveur.printInfo("Erreur de connexion à "+brique);
			serveur.setNTXConnexion(false);
		}
		else{
			outputStream = conn.getDataOut();
			inputStream = conn.getDataIn();
	
			isRunning = true;
			serveur.setNTXConnexion(true);
		}
	}

	public void run(){
		while (isRunning) {
			char c = getCommande();
			if (c == '_'){
			}else{				
				serveur.interprete(c);
			}}
		serveur.printInfo("Fin connexion");
		try {
			inputStream.close();
			outputStream.close();
		} catch (Exception e) {
			serveur.incident();
		}
	}

	public char getCommande() {
		char c = '0';
		while (c=='0')
		{
			try {
				c = inputStream.readChar();
			} catch (IOException e) {
				serveur.incident();
			}			
		}

		return c;
	}
	
	public void kill() {
		send('.');
		isRunning = false;
		serveur.setNTXConnexion(false);
	}
	
	public void send(char commande){
		try{
			outputStream.writeChar(commande);
			outputStream.flush();
		} catch (IOException e) {
			serveur.incident();
		}			
	}
}
